package Utils;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

public class IdCardVerify {

    public static final int[] W = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
    public static final String PATTERN = "[1-9][\\d]{16}[x|X|0-9]";
    public static final Map<Integer, String> VAR_MPA = new HashMap<>();

    static {
        VAR_MPA.put(0, "1");
        VAR_MPA.put(1, "0");
        VAR_MPA.put(2, "x");
        VAR_MPA.put(3, "9");
        VAR_MPA.put(4, "8");
        VAR_MPA.put(5, "7");
        VAR_MPA.put(6, "6");
        VAR_MPA.put(7, "5");
        VAR_MPA.put(8, "4");
        VAR_MPA.put(9, "3");
        VAR_MPA.put(10, "2");
    }

    public static boolean isVerify(String idCard) {
        if (idCard != null && Pattern.matches(PATTERN, idCard)) {
            String numArea = idCard.substring(0, 17);
            String last = idCard.substring(17);
            int totalNum = 0;
            for (int i = 0; i < W.length; i++) {
                totalNum += Integer.parseInt(String.valueOf(numArea.charAt(i))) * W[i];
            }
            int preVer = totalNum % 11;
            return last.equalsIgnoreCase(VAR_MPA.get(preVer));
        }
        return false;
    }
}
